JavaScript Prototypes and Iterables

Prototype Basics

In JavaScript, every object has a prototype. A prototype is also an object from which other objects inherit properties.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <Script>
        // Example of prototype inheritance
        function Person(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }
        Person.prototype.fullName = function() {
            return this.firstName + " " + this.lastName;
        };
        const Akef = new Person('Akef', 'Khan');
        console.log(Akef.fullName()); // Output: Akef Khan
    </Script>
</body>
</html>
                             
Output: Akef Khan
Prototype Inheritance Diagram

Iterables

In JavaScript, iterables are objects that can be iterated over, such as arrays, strings, maps, sets, etc. Iterators define a method that returns an object with a 'next()' method.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <Script>
        // Example of custom iterable object
        const myIterable = {
            *[Symbol.iterator]() {
                yield 1;
                yield 2;
                yield 3;
            }
        };
        for (const value of myIterable) {
            console.log(value); // Output: 1, 2, 3
        }
    </Script>
</body>
</html>
                                
Output:
1
2
3
Iterable Process

Prototypes with Iterables

We can also combine prototypes and iterables by defining iterable behavior on the prototype of an object.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <Script>
        // Prototype and Iterable combined
        function Collection() {
            this.items = [];
        }
        Collection.prototype.add = function(item) {
            this.items.push(item);
        };
        Collection.prototype[Symbol.iterator] = function* () {
            for (let item of this.items) {
                yield item;
            }
        };
        const myCollection = new Collection();
        myCollection.add('Apple');
        myCollection.add('Banana');
        for (const item of myCollection) {
            console.log(item); // Output: Apple, Banana
        }
    </Script>
</body>
</html>
                               
Output:
Apple
Banana